<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        {{ $t('user.DesktopUserPageTitle') }}
        <i v-if="false" class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <el-scrollbar class="page-content">
      <div class="content-wrapper">
        <el-card>
          <basic-table
            ref="BasicTable"
            :pageMethod="getTableData"
          >
            <template #table-options="tableSlotData">
              <div class="table-left-options">
                <!-- <el-button v-if="AuthModule.authrole == 'system_admin'" class="icon-button setting-button" style="width: auto;" @click="deleteDesktopUser(tableSlotData.table.selectRows)" :disabled="tableSlotData.table.selectRows.length <= 0">
                  <i class="el-icon-delete" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{ $t('common.BatchDelete') }}</span>
                </el-button> -->
                <el-button class="icon-button setting-button" style="width: auto;" :disabled="tableSlotData.table.selectRows.length <= 0" @click="() => {
                  $tunnyApi.apiBatchUserAction('desktop_user', tableSlotData.table.selectRows, 'enable').then(() => {
                    tableSlotData.table.refresh();
                    $message({
                      message: $t('desktopManage.message.operationSuccess', {operation: $t('user.Enable')}).toString(),
                      type: 'success'
                    });
                  }).catch(() => {
                    $message({
                      message: $t('desktopManage.message.operationFail', {operation: $t('user.Enable')}).toString(),
                      type: 'warning'
                    });
                  });
                }">
                  <i class="el-icon-check" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{ $t('user.Enable') }}</span>
                </el-button>
                <el-button class="icon-button setting-button" style="width: auto;" :disabled="tableSlotData.table.selectRows.length <= 0" @click="() => {
                  $tunnyApi.apiBatchUserAction('desktop_user', tableSlotData.table.selectRows, 'disable').then(() => {
                    tableSlotData.table.refresh();
                    $message({
                      message: $t('desktopManage.message.operationSuccess', {operation: $t('user.Disable')}).toString(),
                      type: 'success'
                    });
                  }).catch(() => {
                    $message({
                      message: $t('desktopManage.message.operationFail', {operation: $t('user.Disable')}).toString(),
                      type: 'warning'
                    });
                  });
                }">
                  <i class="el-icon-close" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{ $t('user.Disable') }}</span>
                </el-button>
                <el-dropdown style="margin-left: 10px;" @command="(cmd) => { switch(cmd) {
                  case 'set-login-timeslot':
                    $refs.SetLoginTimeslotDialop.init(tableSlotData.table.selectRows);
                    break;
                  case 'reset--login-fail-count':
                    resetLoginFailCountLoading = true;
                    $tunnyApi.apiResetLoginFailCount(tableSlotData.table.selectRows, { auth_failed_times: 0 }).then(()=>{
                      $message.success($t('user.resetCountSuccess'));
                    }).catch(()=> {
                      $message.error($t('user.resetCountFail'));
                    }).finally(() => {
                      resetLoginFailCountLoading = false;
                    });
                    break;
                  case 'enable-SMS':
                      $refs.EnableSMS.init(tableSlotData.table.selectRows,true);
                      break;
                  case 'close-SMS':
                    $refs.CloseSMS.init(tableSlotData.table.selectRows, true);
                    break;
                } }" :hide-on-click="false">
                  <el-button class="icon-button setting-button" style="width: auto;">
                    <span style="font-size: 12px;">{{$t('common.More')}}</span>
                    <i class="el-icon-arrow-down el-icon--right" style="font-size: 12px; margin-left: 5px;"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :disabled="tableSlotData.table.selectRows.length <= 0" :command="'set-login-timeslot'">{{ $t('user.SetLoginTimeslot') }}</el-dropdown-item>
                    <el-dropdown-item :disabled="tableSlotData.table.selectRows.length <= 0 || resetLoginFailCountLoading" :command="'reset--login-fail-count'">{{ $t('user.ResetLoginFailCount') }}<i v-if="resetLoginFailCountLoading" class="el-icon-loading" style="color: #333333; margin-left: 5px;"></i></el-dropdown-item>
                    <el-dropdown-item :disabled="tableSlotData.table.selectRows.length <= 0" :command="'enable-SMS'">{{ $t("user.EnableSMS") }}</el-dropdown-item>
                    <el-dropdown-item :disabled="tableSlotData.table.selectRows.length <= 0" :command="'close-SMS'">{{ $t("user.CloseSMS") }}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="table-right-options">
                <el-select v-model="searchPoolId" filterable default-first-option :placeholder="$t('user.resourcePoolSelectPlaceholder')" @change="getResourceList" @clear="getResourceList" :disabled="poolSelectLoading" style="width: 200px; margin-right: 10px;" clearable>
                  <el-option
                    v-for="pool in poolList"
                    :key="pool.id"
                    :label="pool.name"
                    :value="pool.id">
                  </el-option>
                </el-select>
                <el-select v-model="searchResourceId" filterable default-first-option :placeholder="$t('user.resourceTenantSelectPlaceholder')" @change="tableSlotData.table.refresh(true)" :disabled="resourceSelectLoading" style="width: 200px; margin-right: 10px;">
                  <el-option
                    v-for="(resource, index) in resourceList"
                    :key="index"
                    :label="resource.name"
                    :value="resource.id + '_' + resource.resource_type">
                  </el-option>
                </el-select>
                <el-input :placeholder="$t('user.DesktopUserPageTableSearchPlaceholder')" @keyup.enter.native="tableSearchChange(tableSlotData)" v-model="searchValue" style="width: 200px;" >
                </el-input>
                <el-button @click="tableSearchChange(tableSlotData)" type="primary" style="margin-left: 10px;" >{{ $t('common.search') }}</el-button>
              </div>
            </template>
            <template #table-column="tableSlotData">
              <el-table-column type="selection" width="40" align="center"></el-table-column>
              <el-table-column
                prop="resource_pool_name"
                :label="$t('user.ResourcePool')"
              >
                <!-- <template #default="props">
                  <link-button :content="props.row.resource_pool_name" :size="10" :font-size="'12px'" @click="$router.push({
                    name: 'PoolDetail',
                    query: {
                      poolid: props.row.resource_pool_id
                    }
                  })" />
                </template> -->
              </el-table-column>
              <el-table-column
                prop="resource_name"
                :label="$t('user.ResourceTenant')"
              >
              </el-table-column>
              <el-table-column
                prop="name"
                :label="$t('user.ADUserName')"
              >
                <template #default="props">
                  <div style="width:100%;display:flex;justify-content:flex-start;align-items: center">
                    <link-button :content="props.row.name" style="max-width:80%" :isName="true" :size="1" :font-size="'12px'" @click="$router.push({
                      name: 'UserDesktopUserDetail',
                      query: {
                        id: props.row.id
                      }
                    })" />
                    <el-tooltip class="item" effect="dark" :content="props.row.enabled === true ? $t('user.isEnabled') : (props.row.enabled === false ? $t('user.isDisabled') : $t('common.unknown'))" placement="bottom-start">
                        <i v-if="props.row.enabled === true" class="iconfont iconzhongyiicon_yunxu" style="font-size: 12px; margin-left: 5px; color: #10C038"></i>
                        <i v-else-if="props.row.enabled === false" class="iconfont iconzhongyiicon_guaqi" style="font-size: 12px; margin-left: 5px; color: #F04134"></i>
                        <i v-else class="iconfont iconzhongyiicon_gaojing" style="font-size: 12px; margin-left: 5px; color: #FF931D"></i>
                      </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="cloud_tenant_name"
                v-if="AuthModule.authrole === 'system_admin'"
                :label="$t('user.BelongTenant')"
              >
              </el-table-column>
              <el-table-column
                prop="pretty_name"
                :label="$t('user.Alias')"
              >
              </el-table-column>
              <el-table-column :label="$t('user.allowLoginTime')">
                <template #default="props">
                  {{initTime(props.row.auth_time_window)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('user.mobile')" prop="mobile" width="163px">
                <template #default="props">
                  <div class="mobileitems">
                    <span>{{props.row.mobile}}</span>
                    <div style="height:16px;">
                      <el-tooltip class="item" effect="dark" :content="$t('user.enableSMSHover')" placement="right">
                        <i class="iconfont iconduanxinrenzheng"
                          style="margin-left:6px;color:#037DFF;"
                          v-show="props.row.enable_sms_certification === true"></i>
                      </el-tooltip>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('user.Action')"
                width="220"
              >
                <template #default="props">
                  <!-- <link-button :content="$t('user.Delete')" :size="10" :font-size="'12px'" @click="deleteDesktopUser([props.row])" style="margin-right: 15px;" /> -->
                  <link-button :content="$t('user.PasswordReset')" :size="10" :font-size="'12px'" @click="resetPassword(props.row)" style="margin-right: 15px;" />
                  <el-dropdown style="margin-left: 10px;cursor: pointer;" @command="(cmd) => {
                    switch(cmd) {
                      case 'enable':
                        $tunnyApi.apiBatchUserAction('desktop_user', [props.row], 'enable').then(() => {
                          tableSlotData.table.refresh();
                          $message({
                            message: $t('desktopManage.message.operationSuccess', {operation: $t('user.Enable')}).toString(),
                            type: 'success'
                          });
                        }).catch(() => {
                          $message({
                            message: $t('desktopManage.message.operationFail', {operation: $t('user.Enable')}).toString(),
                            type: 'warning'
                          });
                        });
                        break;
                      case 'disable':
                        $tunnyApi.apiBatchUserAction('desktop_user', [props.row], 'disable').then(() => {
                          tableSlotData.table.refresh();
                          $message({
                            message: $t('desktopManage.message.operationSuccess', {operation: $t('user.Disable')}).toString(),
                            type: 'success'
                          });
                        }).catch(() => {
                          $message({
                            message: $t('desktopManage.message.operationFail', {operation: $t('user.Disable')}).toString(),
                            type: 'warning'
                          });
                        });
                        break;
                      case 'set-alias':
                        $refs.SetAliasDialog.init(props.row);
                        break;
                      case 'bind-telephone':
                        $refs.BindTelephone.init(props.row);
                        break;
                      case 'unbind-telephone':
                          $refs.UnbindTelephone.init(props.row);
                          break
                      case 'enable-SMS':
                        $refs.EnableSMS.init(props.row);
                        break;
                      case 'close-SMS':
                        $refs.CloseSMS.init(props.row, false);
                        break;
                    }
                  }">
                    <span class="el-dropdown-link">
                      {{$t('user.More')}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="'enable'" :disabled="props.row.enabled === null ? false : props.row.enabled">{{ $t('user.Enable') }}</el-dropdown-item>
                      <el-dropdown-item :command="'disable'" :disabled="props.row.enabled === null ? false : !props.row.enabled">{{ $t('user.Disable') }}</el-dropdown-item>
                      <el-dropdown-item :command="'set-alias'">{{ $t('user.SetAlias') }}</el-dropdown-item>
                      <el-dropdown-item :command="'bind-telephone'">{{ $t("user.bindMobile") }}</el-dropdown-item>
                      <el-dropdown-item :command="'unbind-telephone'" :disabled="props.row.mobile == ''">{{ $t("user.unbindMobile") }}</el-dropdown-item>
                      <el-dropdown-item v-if="props.row.enable_sms_certification === false" :disabled="props.row.mobile === ''" :command="'enable-SMS'">{{ $t("user.EnableSMS") }}</el-dropdown-item>
                      <el-dropdown-item v-else :command="'close-SMS'">{{ $t("user.CloseSMS") }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
            <template #others-elements="tableSlotData">
              <set-login-timeslot-dialop ref="SetLoginTimeslotDialop" :submit-method="(timeslot) => $tunnyApi.apiBatchPutUser('desktop_user', tableSlotData.table.selectRows, { auth_time_window: timeslot }, true).then(() => {
                $message.success($t('user.setLoginTimeSuccess'))
                tableSlotData.table.refresh();
              }).catch(()=>{
                $message.warning($t('user.setLoginTimeFail'))
                tableSlotData.table.refresh();
              })" />
              <delete-dialog ref="DeleteDialog" :delete-method="(itemList) => $tunnyApi.apiBatchDeleteUser('desktop_user', itemList).then(() => {
                tableSlotData.table.deleteRefresh(itemList.length);
              })" />
              <reset-password-dialog ref="ResetPasswordDialog" :reset-method="(item, formData) => $tunnyApi.apiBatchUserAction('desktop_user', [item], 'passwd', { password: formData.new_password }).then(() => {
                tableSlotData.table.refresh();
              })" />
              <set-alias-dialog ref="SetAliasDialog" :submit-method="(item, formData) => $tunnyApi.apiSetUserAlias('desktop_user', [item], { pretty_name: formData.alias }).then((res) => {
                if (!res.id) {
                  if(res.msg[0].indexOf('already exist')){
                    $message.error($t('user.aliasExists'));
                  } else {
                    $message.success($t('user.aliasSuccess'));
                    tableSlotData.table.refresh();
                  } 
                } else {
                  $message.success($t('user.aliasSuccess'));
                  tableSlotData.table.refresh();
                }
              })" />
              <bind-telephone ref="BindTelephone" :submit-method="(item, formData) => $tunnyApi.apiSetUserMobile('desktop_user', [item], { mobile: formData.mobile }).then((res) => {
                if (res.id) {
                  $message.success($t('user.bindMobileSuccess'));
                  tableSlotData.table.refresh();
                } else {
                  $message.warning($t('user.bindMobileFail'));
                }
              })"></bind-telephone>
              <unbind-mobile ref="UnbindTelephone" :submit-method="(item, formData) => $tunnyApi.apiSetUserMobile('desktop_user', [item], { mobile: formData.mobile }).then((res) => {
                if (res.id) {
                  $message.success($t('user.unbindMobileSuccess'));
                  tableSlotData.table.refresh();
                } else {
                  $message.warning($t('user.unbindMobileFail'));
                }
              })"></unbind-mobile>
              <enable-sms ref="EnableSMS" :submit-method="(data) => $tunnyApi.apiSetUserSms(data).then((res) => {
                if (res.code === 2000) {
                  $message.success($t('user.enableSmsSuccess'));
                  tableSlotData.table.refresh();
                } else {
                  $message.warning($t('user.enableSmsFail'));
                }
              })" @clearSelect="clearSelect"></enable-sms>
              <close-sms ref="CloseSMS" @success='success'></close-sms>
            </template>
          </basic-table>
        </el-card>
      </div>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import BasicTable from '../../components/Basic/Table/BasicTable.vue';
import LinkButton from '../../components/Basic/Button/LinkButton.vue';
import SetLoginTimeslotDialop from './components/SetLoginTimeslotDialop.vue';
import DeleteDialog from './components/DeleteDialog.vue';
import ResetPasswordDialog from './components/ResetPasswordDialog.vue';
import { AuthModule } from '../../store/modules/auth';
import SetAliasDialog from './components/SetAliasDialog.vue';
import BindTelephone from './components/BindTelephone.vue';
import unbindMobile from './components/unBindTelephone.vue';
import EnableSms from './components/EnableSMS.vue';
import CloseSms from './components/CloseSMS.vue';
export default Vue.extend({
  components: {
    BasicTable,
    LinkButton,
    SetLoginTimeslotDialop,
    DeleteDialog,
    ResetPasswordDialog,
    SetAliasDialog,
    BindTelephone,
    unbindMobile,
    EnableSms,
    CloseSms
  },
  computed: {
    AuthModule: () => AuthModule
  },
  data() {
    return {
      searchValue: "",
      searchPoolId: "",
      searchTenantId: "",
      searchResourceId: "", 
      poolList: [],
      tenantList: [],
      resourceList: [],
      poolSelectLoading: false,
      tenantSelectLoading: false,
      resourceSelectLoading: false,
      resetLoginFailCountLoading: false,
      tableInputSearch: false
    };
  },
  async created() {
    await (this as any).getPoolList();
  },
  methods: {
    success() {
      (this as any).$refs.BasicTable.refresh();
    },
    clearSelect(rows: any) {
      console.log((this as any).$refs.BasicTable);
      (this as any).$refs.BasicTable.$refs["el-table"].clearSelection();
    },
    tableSearchChange(table: any) {
      (this as any).tableSearch = true;
      table.table.refresh(true);
    },
    initTime(timer: any) {
      let time = JSON.parse(timer);
      let start = parseInt(time.start / 60 as any) + ":" + (time.start - parseInt(time.start / 60 as any) * 60);
      let end = parseInt(time.end / 60 as any) + ":" + (time.end - parseInt(time.end / 60 as any) * 60);
      let start_h = start.split(":")[0]
      let start_m = start.split(":")[1]
      if(start_h.length < 2){
        start_h = '0' + start_h
      }
      if(start_m.length < 2){
        start_m = '0' + start_m
      }
      start = start_h + ":" + start_m
      let end_h = end.split(":")[0]
      let end_m = end.split(":")[1]
      if(end_h.length < 2){
        end_h = '0' + end_h
      }
      if(end_m.length < 2){
        end_m = '0' + end_m
      }
      end = end_h + ":" + end_m
      return start + '-' + end;
    },
    async getPoolList() {
      (this as any).poolSelectLoading = true;
      await (this as any).$pandaApi.apiGetResourceList({}).then((res: any) => {
        res = res.sort((a: any, b: any) => (a.name).localeCompare((b.name), 'zh-Hans-CN', { sensitivity: 'accent' }));
        (this as any).poolList = res;
      });
      (this as any).poolSelectLoading = false;
    },
    async getTenantList() {
      (this as any).tenantSelectLoading = true;
      await (this as any).$tunnyApi.apiGetTenantList({}).then((res: any) => {
        res = res.sort((a: any, b: any) => (a.name).localeCompare((b.name), 'zh-Hans-CN', { sensitivity: 'accent' }));
        (this as any).tenantList = res;
      });
      (this as any).tenantSelectLoading = false;
    },
    async getResourceList() {
      const pool = (this as any).poolList.find((pool: any) => pool.id === (this as any).searchPoolId);
      if (!pool) {
        (this as any).searchResourceId = "";
        (this as any).resourceList = [];
        (this as any).$refs.BasicTable.refresh(true);
        return;
      }
      (this as any).resourceSelectLoading = true;
      let arr: any = [];

      if(AuthModule.authrole == "system_admin") {
        const daasResourceList = await (this as any).$pandaApi.apiGetDaaSTenantList({ pool_id: pool.id });
        if (daasResourceList.length > 0) {
          arr.push(...daasResourceList);
        }
        const horizonResourceList = await (this as any).$pandaApi.apiGetHorizonTenantList({ pool_id: pool.id });
        if (horizonResourceList.length > 0) {
          arr.push(...horizonResourceList);
        }
      }else {
        const arr2 = await (this as any).$pandaApi.apiGetResourceTenantsList(pool.id);
        if(arr2.length > 0) {
          arr.push(...arr2);
        }
      }
      
      (this as any).resourceList = arr;

      if((this as any).resourceList.length > 0) {
        (this as any).searchResourceId = (this as any).resourceList[0].id + '_' + (this as any).resourceList[0].resource_type;
        (this as any).$refs.BasicTable.refresh(true);
      }else {
        (this as any).searchResourceId = "";
      }

      (this as any).resourceSelectLoading = false;
    },
    deleteDesktopUser(itemList: any) {
      (this as any).$refs.DeleteDialog.init({
        type: 'desktop_user',
        itemList
      });
    },
    resetPassword(row: any) {
      (this as any).$refs.ResetPasswordDialog.init({
        item: row,
        type: 'desktop_user'
      });
    },
    /**
     * 桌面用户表格查询方法
     * @param params 表格组件分页参数
     */
    async getTableData(params: any) {
      // 模糊查询和租户选择框
      params.search = (this as any).searchValue;
      if ((this as any).tableSearch) {
        params.page = 1;
        (this as any).tableSearch = false;
      }
      params.cloud_tenant = AuthModule.authrole === 'tenant_admin' ? AuthModule.cloud_tenant_id : (this as any).searchTenantId;

      // 资源池-资源租户级联查询操作
      const resource = (this as any).resourceList.find((resource: any) => (resource.id + '_' + resource.resource_type) === (this as any).searchResourceId);
      if (resource) {
        // const activeDirectory = (await (this as any).$tunnyApi.apiGetActiveDirectorys({ resource_type: resource.resource_type, resource_id: resource.id }))[0];

        // if (activeDirectory) {
        //   params.active_directory = activeDirectory.id;
        // }

        params.resource_type = resource.resource_type;
        params.resource_id = resource.id;
      } else {

        if (this.searchPoolId) {
          params.resource_type = '';
          params.resource_id = '';
        }
      }

      // 调用桌面用户查询接口
      const result = await (this as any).$tunnyApi.getDesktopUserList(params);

      // 循环查询每条桌面用户的资源租户信息
      for (let i = 0; i < result.rows.length; i++) {
        const resourceInfo = await (this as any).$pandaApi.apiGetResourceInfoInUser(result.rows[i].resource_type, result.rows[i].resource_id);
        result.rows[i].resource_name = resourceInfo.name;
        result.rows[i].resource_pool_name = resourceInfo.resource_pool_name;
        result.rows[i].resource_pool_id = resourceInfo.resource_pool;
      }

      return result;
    }
  }
})
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #EFF1F4;

  .page-header {
    height: 60px;
    background-color: #FFFFFF;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #D9D9D9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;
    }
  }

  .mobileitems {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}

.table-left-options {
  display: flex;
}

.table-right-options {
  display: flex;

  .setting-button {
    margin-right: 10px;
  }
}

.delete-warning-icon {
  color: #FF931D;
  font-size: 20px;
  margin-right: 10px;

  &::before {
    font-size: 20px;
  }
}
</style>
